package com.cardbaobao.cardbabyclient.ui.fragment.findbank;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.ui.adapter.base.CommonAdapter;
import com.cardbaobao.cardbabyclient.ui.adapter.base.ViewHolder;
import com.cardbaobao.cardbabyclient.ui.fragment.base.BaseFragment;
import com.cardbaobao.cardbabyclient.model.BankPhone;
import com.cardbaobao.cardbabyclient.model.ServiceBanks;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.widget.LetterListView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;

/**
 * 银行电话
 * Created by zad
 * 2017/1/10 14:01
 */

public class BankPhoneFragment extends BaseFragment implements LetterListView.OnTouchingLetterChangedListener {
    private String prePageId;
    public void setBuriedInfo(String prePageId){
        this.prePageId=prePageId;
    }
    /**银行电话列表*/
    @BindView(R.id.id_lv_bank_phone)
    ListView mLvBankPhone;
    /**右侧字母列表*/
    @BindView(R.id.id_letter_view)
    LetterListView mLvLetter;
    /**居中字母提示*/
    @BindView(R.id.id_tv_letter_show)
    TextView mTvLetterShow;
    /**顶部悬浮字母布局*/
    @BindView(R.id.id_ll_title_letter)
    LinearLayout mLLTitleLetter;
    /**顶部悬浮字母*/
    @BindView(R.id.id_tv_letter)
    TextView mTvLetter;
    /**没有数据提示*/
    @BindView(R.id.ll_no_data)
    LinearLayout llNoData;
    /**银行电话列表适配器*/
    private CommonAdapter<ServiceBanks> mBankPhoneAdapter;
    /**
     * 银行电话列表
     */
    private List<ServiceBanks> mServiceBankList;
    /**
     * 右侧字母列表
     */
    private List<String> mLetterList;
    /**
     * 总的字母列表 用于滑动位置检索
     */
    private List<String> mLetterTotalList;

    @Override
    protected void initViewFinish(View view, Bundle savedInstanceState) {

        mCurrentPageId= Self.Page.app_bank_tel_page;

        mTvLetterShow.setVisibility(View.GONE);//字母中部提示
        mLvLetter.setVisibility(View.GONE);//字母列表
        mLvLetter.setOnTouchingLetterChangedListener(this);
        Observable<String> observable= Api.bankTelList();
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                dismissProgressDialog();
            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                List<BankPhone> data=JsonUtil.getDataLists(s, BankPhone.class);
                setBankPhoneList(data);
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_bank_phone;
    }

    /**
     * 右侧字母触摸回调
     */
    @Override
    public void onTouchingLetterChanged(String text, boolean isShow) {
        //触摸右侧列表回调
        if (isShow) {
            mTvLetterShow.setVisibility(View.VISIBLE);
            mTvLetterShow.setText(text);
            mLvBankPhone.setSelection(getPositionForSection(text.charAt(0), false));
        } else {
            mTvLetterShow.setVisibility(View.GONE);
        }
    }

    /**
     * 设置银行电话列表
     * @param tempLists 接口原始数据
     */
    private void setBankPhoneList(List<BankPhone> tempLists) {
        mServiceBankList = splitBankPhoneList(tempLists);
        if (mServiceBankList != null && mServiceBankList.size() > 0) {
            showList(true);
            mBankPhoneAdapter = new CommonAdapter<ServiceBanks>(mContext, mServiceBankList, R.layout.item_bank_phone_two) {
                @Override
                public void convert(ViewHolder holder, final ServiceBanks item, int position) {
                    holder.setText(R.id.id_tv_bank_title, item.getTitle());//银行名称
                    View view_tel = holder.getView(R.id.id_ll_tel);//打电话布局
                    view_tel.setVisibility(View.VISIBLE);
                    holder.setText(R.id.id_tv_tel, item.getTel());//银行电话
                    view_tel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            SelfUtils.buriedClickData(Self.Action.app_click_near_by_bank_tel_item,
                                    Self.Action.app_click_near_by_bank_tel_item_des,
                                    mEnterPageTime,
                                    mCurrentPageId,
                                    prePageId);
                            //打电话
                            call(item.getTel());
                        }
                    });

                    //银行logo
                    holder.displayImage(R.id.id_iv_bank_logo,
                            URLUtil.CBB_IMG_URL + item.getLogoUrl(),
                            R.mipmap.img_default_square);
                    //设置字母是否显示
                    TextView tv_letter = holder.getView(R.id.id_tv_letter);
                    if (position == 0 || !TextUtils.equals(item.getTop(), mServiceBankList.get(position - 1).getTop())) {
                        tv_letter.setVisibility(View.VISIBLE);
                        tv_letter.setText(item.getTop());
                    } else {
                        //当前首字母等于前一个首字母
                        tv_letter.setVisibility(View.GONE);
                    }
                }
            };
            mLvBankPhone.setAdapter(mBankPhoneAdapter);
            setLetterList();
            setListViewScrollEvent();
        } else {
            //没有数据
            showList(false);
        }
    }

    private void showList(boolean showList){
        if(showList){
            mLvBankPhone.setVisibility(View.VISIBLE);
            llNoData.setVisibility(View.GONE);
        }else{
            mLvBankPhone.setVisibility(View.GONE);
            llNoData.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 拆分原始银行列表数据
     */
    private List<ServiceBanks> splitBankPhoneList(List<BankPhone> tempLists) {
        if (tempLists != null && tempLists.size() > 0) {
            List<ServiceBanks> mServiceBanks = new ArrayList<>();
            for (int i = 0, len = tempLists.size(); i < len; i++) {
                BankPhone bankPhone = tempLists.get(i);
                if (bankPhone != null) {
                    for (ServiceBanks serviceBank : bankPhone.getBanks()) {
                        if (i == 0) {
                            //热门
                            String letter = bankPhone.getTop();
                            serviceBank.setTop(letter);
                            mServiceBanks.add(serviceBank);
                        } else {
                            //非热门
                            mServiceBanks.add(serviceBank);
                        }
                    }
                }
            }
            return mServiceBanks;
        }
        return null;
    }

    /**
     * 设置拼音列表
     */
    private void setLetterList() {
        mLetterList = new ArrayList<>();
        mLetterTotalList = new ArrayList<>();
        for (int i = 0, len = mServiceBankList.size(); i < len; i++) {
            String letter = mServiceBankList.get(i).getTop();
            //用于滑动位置检索
            mLetterTotalList.add(letter);
            //用于右侧字母列表显示
            if (!mLetterList.contains(letter)) {
                mLetterList.add(letter);
            }
        }
        mLvLetter.setPinyinList(mLetterList);
        mLvLetter.setVisibility(View.VISIBLE);
    }

    /**
     * 　根据分类的首字母的Char值获取位置
     * @param section           当前字母的char值
     * @param isGetNextPosition 是否是获取下一个字母位置
     */
    public int getPositionForSection(int section, boolean isGetNextPosition) {
        for (int i = 0, l = mLetterTotalList.size(); i < l; i++) {
            String letter = mLetterTotalList.get(i);
            char letterChar = letter.toUpperCase().charAt(0);
            if (!isGetNextPosition) {
                //获取当前字母第一次出现的位置
                if (letterChar == section) {
                    return i;
                }
            } else {
                //获取当前字母后一个字母出现的位置
                if (letterChar > 90) letterChar = 0;//处理汉字的情况， Z == 90
                if (section > 90) section = 0;//处理汉字的情况， Z == 90
                if (letterChar > section) {
                    return i;
                }
            }
        }
        return -1;
    }

    /**
     * 拨打电话
     */
    private void call(String phoneNumber) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:" + phoneNumber));
        if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
            //查询是否存在这个Activity 有的话跳转
            startActivity(intent);
        }
    }

    /**
     * 上次第一个可见元素，用于滚动时记录标识。
     */
    private int lastFirstVisibleItem = -1;

    /**
     * 设置列表滚动事件监听
     */
    private void setListViewScrollEvent() {
        mLvBankPhone.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                int section = mLetterTotalList.get(firstVisibleItem).charAt(0);//获取当前字母的char值
                int nextSecPosition = getPositionForSection(section, true);//下一个字母出现的位置
                if (firstVisibleItem != lastFirstVisibleItem) {
                    //当前显示的位置不是上一次显示的位置，顶部标题复位
                    mLLTitleLetter.setTranslationY(0);
                    mTvLetter.setText(mLetterTotalList.get(firstVisibleItem));
                }
                if (nextSecPosition == firstVisibleItem + 1) {
                    //屏幕上方当前显示的下一个Item位置和下一个字母出现的位置相同
                    View childView = view.getChildAt(0);
                    if (childView != null) {
                        int titleHeight = mLLTitleLetter.getHeight();
                        int bottom = childView.getBottom();
                        if (bottom < titleHeight) {
                            //下一个标题接触到顶部标题时，顶部标题滚动
                            float scrollDistance = bottom - titleHeight;//滚动距离
                            mLLTitleLetter.setTranslationY(scrollDistance);
                        } else {
                            //当下一个标题和顶部标题分离时，标题复位
                            if (mLLTitleLetter.getTranslationY() != 0) {
                                mLLTitleLetter.setTranslationY(0);
                            }
                        }
                    }
                }
                lastFirstVisibleItem = firstVisibleItem;
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        mTvLetterShow.setVisibility(View.GONE);
    }
}
